import type { App } from 'vue'
import { createI18n } from 'vue-i18n'
import { LanguageEnum } from '@/enums/appEnum'
import { useAppStoreWithOut } from '@/stores/modules/app'
import antdEnUs from 'ant-design-vue/es/locale/en_US'
import antdZhCn from 'ant-design-vue/es/locale/zh_CN'
import dayjs from 'dayjs'
import dayjsEn from 'dayjs/locale/en'
import dayjsZhCn from 'dayjs/locale/zh-cn'

const messagesFiles: any = import.meta.glob('./langs/**/*.ts', { eager: true })

// state
const messagesMap = Object.keys(messagesFiles).reduce((acc: any, path) => {
  const fileName = path.split('/').pop()?.replace('.ts', '') || path
  acc[fileName] = messagesFiles[path].default
  return acc
}, {})
const dayjsMessagesMap = {
  [LanguageEnum.ZH_CN]: dayjsZhCn,
  [LanguageEnum.EN_US]: dayjsEn
}
export const antdLocaleMap = {
  [LanguageEnum.ZH_CN]: antdZhCn,
  [LanguageEnum.EN_US]: antdEnUs
}

/**
 * 创建国际化对象
 */
const create = () => {
  const i18n: any = createI18n({
    locale: '',
    fallbackLocale: '',
    messages: {}
  })

  // 修改国际化方法
  i18n.global.$t = i18n.global.t // 保存原有方法
  i18n.global.t = (key: string, _desc?: string) => {
    return i18n.global.$t(key)
  }
  return i18n
}
const i18n = create()

/**
 * 设置dayjs的语言包
 * @param lang
 */
const setDayjsLocale = async (lang: LanguageEnum) => {
  if (!dayjsMessagesMap[lang]) {
    throw new Error('语言包不存在')
  }
  dayjs.locale(dayjsMessagesMap[lang]) // 设置dayjs的语言
}

/**
 * 初始化设置国际化
 */
const setupI18n = async (app: App) => {
  const appStore = useAppStoreWithOut()
  setLang(appStore.language) // 设置语言
  app.use(i18n)
}

/**
 * 设置语言
 * @param locale
 */
const setLang = (locale: LanguageEnum) => {
  if (!messagesMap[locale]) {
    throw new Error('语言包不存在')
  }
  i18n.global.setLocaleMessage(locale, messagesMap[locale])
  i18n.global.locale = locale
  setDayjsLocale(locale)
  const appStore = useAppStoreWithOut()
  appStore.setLanguage(locale)
}

const $t = i18n.global.t
export { $t, i18n, setLang, setupI18n }
